package com.wanaofu.service;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.wanaofu.dao.QueryDAO;
import com.wanaofu.dao.UniversalDAO;
import com.wanaofu.model.AbstractWarehouseBatch;
import com.wanaofu.model.WarehouseBalance;
import com.wanaofu.model.WarehouseBatchItem;

@Service
@Validated
public class OperateWarehouseService {
	@Resource
	private UniversalDAO uidDao ;
	@Resource
	private QueryDAO queryDao ;
	
	/**
	 * 
	 * @param batch
	 */
	public void saveOperateWarehouse(@NotNull(message="单据" + "{waf.validation.NotNull.message}")
	                                 @Valid    
	                                 AbstractWarehouseBatch batch)  
	{
		//validating
		validating(batch);
		//save into warehouse
		uidDao.save(batch);
		
		//update into balance
		String batchNo = batch.getBatchNo() ;
		for (WarehouseBatchItem item : batch.getDistinctItems()) {
			WarehouseBalance bal = queryDao.findBalance(item.getPosition(),item.getProduct(),batchNo) ;
			if (bal == null) {
				bal = new WarehouseBalance(item.getPosition(),item.getProduct(),batchNo,item.getAmount()) ;
			} else {
				bal.setBalanceAmout(bal.getBalanceAmout() + batch.affectBalceAmount(item.getAmount())) ;
			}
			uidDao.save(bal);
//			throw new RuntimeException();
		}
        

	}
    /**
     * 
     * @param batch
     */
	public void saveContraOperateWarehouse(AbstractWarehouseBatch batch)  {
		
	}
	
	
	private void validating(AbstractWarehouseBatch batch) {
//		if (batch.get)
//		throw new RuntimeException() ;
		
	}
	
}
